 if(document.getElementById('uri_target'))
 { var url2query = document.getElementById('uri_target').value;
 }
 if(!url2query)
 {
   var url2query = 'http://ibl.mdanderson.org/TCGA/';  
 }

 var src =url2query  +"/S3QL.php?format=json&query=<S3QL><from>collections</from><where><project_id>126</project_id></where></S3QL>";
 s3db_jsonpp_call (src,'collectionDisplay(ans)');
 
 var src =url2query  + "/S3QL.php?format=json&query=<S3QL><from>rules</from><where><project_id>126</project_id></where></S3QL>";
 s3db_jsonpp_call (src,'findRules("", ans, \'where\',\'where_attr_td\')');

 //As soo as the interface is ready, constrain the values in the Rules
 function documentReady() {
   ruleConstrain(document.getElementById('select').value, document.getElementById('select').value+'_rules','where_attr_td',1);   
 }

document.navigation = 0;
document.subjects = array();

function changeFromToRDF() {
if(document.getElementById('uri_target'))
 { 
	if(document.getElementById('uri_target').value.match(/\.rdf/))
		url2query = document.getElementById('uri_target').value;
 }
 if(!url2query)
 {
   var url2query = 'http://ibl.mdanderson.org/TCGA/TCGA.rdf';  
 }
document.getElementById('uri_target').value = url2query;

}

function changeFromToS3DB() {
if(document.getElementById('uri_target'))
 { 
	if(!document.getElementById('uri_target').value.match(/\.rdf/))
		url2query = document.getElementById('uri_target').value;
 }
 if(!url2query)
 {
   var url2query = 'http://ibl.mdanderson.org/TCGA/';  
 }
document.getElementById('uri_target').value = url2query;

}

function fillQueryText(option) {
	 
	 if(!url2query){
	 if(document.getElementById('uri_target'))
		 { 
			if(!document.getElementById('uri_target').value.match(/\.rdf/))
				url2query = document.getElementById('uri_target').value;
		 }
	 }
		 if(!url2query)
		 {
		   var url2query = 'http://ibl.mdanderson.org/TCGA/';  
		 }
		 
	 switch (option) {
	     case "0" :
			 var txt = '';
		 break;
		 
		 case "1" :
	         var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT ?GenomicCharacterization  ?GenomicCharacterizationLabel ?PlatformName ?CGCCLabel ?ArchiveSerialIndex ?SampleName \nFROM <'+url2query+'>\nWHERE {\n?GenomicCharacterization rdf:type :C186 . \nOPTIONAL { ?GenomicCharacterization rdfs:label ?GenomicCharacterizationLabel . }\nOPTIONAL { ?GenomicCharacterization :R191 ?RawData . }\nOPTIONAL { ?GenomicCharacterization :R188 ?Platform . }\nOPTIONAL { ?Platform rdfs:label ?PlatformName . }\nOPTIONAL { ?GenomicCharacterization :R53730 ?CancerGenomicCharacterizationAndSequencingCenters . }\nOPTIONAL { ?CancerGenomicCharacterizationAndSequencingCenters rdfs:label ?CGCCLabel . } \nOPTIONAL { ?GenomicCharacterization :R75362 ?ArchiveSerialIndex .  }\nOPTIONAL { ?GenomicCharacterization :R3979 ?Sample . }\nOPTIONAL { ?Sample rdfs:label ?SampleName . }\n}';
	         break;
	     case "2" :
	          var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT ?DataType ?SampleID ?TissueType ?RawDataLink\nFROM <'+url2query+'>\nWHERE {\n?ClinData a :C194 .\n?ClinData :R249 ?TissueType FILTER regex(?TissueType, "^TEMPORAL|PARIETAL LOBE$") .\nOPTIONAL { ?Sample :R247 ?ClinData .}\nOPTIONAL { ?Sample :R12702 ?SampleID . }\n?Sample :R246 ?Array .\n?Array :R6734 ?DataType FILTER regex(?DataType, "^Expression-genes") .\nOPTIONAL { ?Array :R191 ?RawDataLink . }\n}';
	         break;
		case "3" :
				var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema\nPREFIX rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT ?SampleID ?SiteID ?CGCC ?RawData\nFROM <'+url2query+'>\nWHERE {\n? ClinData :R11470 ?SiteID FILTER regex(?SiteID, "MD Anderson")\n?Sample :R247 ?ClinData .\n?Sample :R12702 ?SampleID .\n?Sample :R246 ?GenomicChar .\n?GenomicChar :R361 ?CGCC FILTER regex(?CGCC, "broad.mit.edu").\n?GenomicChar :R191 ?RawData .\n}';
				 break;
	    case "4" :
			var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT ?SampleID ?RawData ?TissueType\nFROM <'+url2query+'>\nWHERE {\n	?Sample :R247 ?ClinData .\n?ClinData :R11469 ?TissueType FILTER regex(?TissueType, "tumor") .\n?Sample :R12702 ?SampleID .\n	?Sample :R246 ?GenomicChar .\n?GenomicChar :R191 ?RawData .\n}';
			break;
		case "5" :
			var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT ?SampleID ?TissueType ?RawData ?PlatformName\nFROM <'+url2query+'>\nWHERE\n{\n	?Sample :R247 ?ClinData .\n?ClinData :R11469 ?TissueType FILTER regex(?TissueType, "tumor") .\n?Sample :R12702 ?SampleID .\n?Sample :R246 ?GenomicChar .\n?GenomicChar :R191 ?RawData .\n?GenomicChar :R188 ?Platform .\n       ?Platform :R149 ?PlatformName FILTER regex(?PlatformName, "Agilent 8 x 15K Human miRNA") .\n}';
			break;
			case "6" :
				var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nPREFIX s3db: <http://www.s3db.org/core#>\nSELECT ?rule ?Subject ?Predicate ?Object ?ObjectLabel\nFROM <'+url2query+'>\nWHERE\n{\n?rule a s3db:s3dbRule .\n?rule rdfs:subClassOf :P126 .\n?rule rdf:subject ?SubjectURI .\n?SubjectURI rdfs:label ?Subject .\n?rule rdf:predicate ?PredicateURI .\n?PredicateURI rdfs:label ?Predicate .\n?rule rdf:object ?Object .\nOPTIONAL { ?Object rdfs:label ?ObjectLabel . }\n}';
			break;
	 }
	 document.getElementById('query').value = txt;
     
 }
 function send_sparql() {
     var target = document.getElementById('uri_target').value;
	 if(document.getElementById('query_engine_sparql').checked)
	 {
	  var sparqlEngine = "http://www.sparql.org/sparql?query="+encodeURIComponent(document.getElementById("query").value)+ '&default-graph-uri=&stylesheet=/xml-to-html.xsl';
	 }
	 else 
	 {     
		 if(target)
			 var sparqlEngine = target + "/sparql.php?query="+encodeURIComponent(document.getElementById("query").value)+ '&format=html';    
	 }

	 window.open(sparqlEngine, "sparql_result");
 }
 
 
 function clearQuery() {
       document.getElementById('query').innerHTML = '';
	   document.getElementById('query').value = '' ;
 }
 
 function findRules(Cid, ans, sel_id, parent_id) {
       var newDiv=document.createElement('div');
		newDiv.id='rules';
		newDiv.rules = ans;
		document.body.appendChild(newDiv);
		document.rules = array();
		for (i = 0; i < ans.length; i++) {
		  document.rules[ans[i].rule_id]  = ans[i];
		}
		ruleDisplay(Cid, ans, sel_id, parent_id);
  }
  
  function ruleDisplay(Cid, rules, sel_id,parent_id,replace) {
   
   //fill the rules box 
   if(replace)
	 document.getElementById(parent_id).innerHTML = '';	  //clear the parent node
   if(navigator.userAgent.match(/Chrome/)!=null)
	   var selSize=2;
   else {
       selSize=1;
   }
   var str  =  '<select id="' +sel_id + '" onClick="navigate_ontology('+Cid+',document.getElementById(\''+sel_id+'\').childNodes, document.getElementById(\''+sel_id+'\').selectedIndex, \''+parent_id+'\')" size="'+selSize+'">';
  // str  += '<option value="all" style="font-style: italic" object="" object_id="C">(All attributes)</option>';
   var j=0;
   var rules_attr = [];
   for (i = 0; i < rules.length; i++) {
      if(rules[i].object!='UID'){
	  str += '<option subject="'+rules[i].subject+'" subject_id="'+rules[i].subject_id+'" rule_id="'+rules[i].rule_id +'" value= ":R' + rules[i].rule_id + '" class="C' +rules[i].subject_id + '" object="' +rules[i].object + '" object_id="C' +rules[i].object_id + '">R'+ rules[i].rule_id +': '+ rules[i].subject + ' - ' + rules[i].verb + ' - ' +rules[i].object +'</option>';
	  rules_attr[j] = rules[i];
	  j++;
	  }
   }
   str += '</select>';
   //append txt to this div
   
   
   var dataThere = document.getElementById(parent_id).innerHTML;
   if(dataThere!='undefined' && dataThere!='')	 {
   document.getElementById(parent_id).innerHTML = dataThere + str;

   }
   else {
       document.getElementById(parent_id).innerHTML = str;
   }
   document.getElementById(sel_id).rules = rules_attr;
   

}


 function collectionDisplay(ans,parent_box) {
   //alert('ola');
   //document.getElementById(parent_box).innerHTML = str;
   if(navigator.userAgent.match(/Chrome/)!=null)
	   var selSize=2;
   else {
       selSize=1;
   }
   
   var newDiv=document.createElement('div');
   newDiv.id='collections';
   newDiv.collections = ans;
   document.body.appendChild(newDiv);
   document.collections = ans;
   var str  =  '<select id="select" OnClick="ruleConstrain(this.value, this.value+\'_rules\',\'where_attr_td\',1)" size="'+selSize+'">';
   //str +=  '<option value="*">*</option>';
   for (i = 0; i < ans.length; i++) {
      if(ans[i].name!='s3dbVerb'){
	  str += '<option value= "' + ans[i].collection_id + '" varName = "' +ans[i].name + '">' + ans[i].name + ' (C' + ans[i].collection_id + ')</option>';
	 }
   }

   str += '</select><input type="checkbox" id="all_tuples" checked/>All tuples';
   //append txt to this div

   document.getElementById('select_td').innerHTML = str;
}



function ruleConstrain(Cid, id_box,parent_box,replace) {
    var allColl = document.getElementById("collections");
	
	if(Cid!='*')    {
	var Rules = document.getElementById("rules").rules;
	var ActiveRules = new Array();
	for (i = 0; i < Rules.length; i++) {
	 
		if(Rules[i].subject_id==Cid){ 
	 		array_push(ActiveRules, Rules[i]);
			
			//Rules[i].style.display = "none";
		}
		
	}
	
	//now re-write the rules for id-box
	document.subjects[Cid] = ActiveRules;
	ruleDisplay(Cid, ActiveRules, id_box,parent_box,replace)	
	}
}

function queryAddTriple(sub, pred, obj) {
    if(!document.query) {document.query= new array();}
	if(!document.query.triple) {document.query.triple = new array();}
	if(!document.query.prefix) {document.query.prefix= new array();	}
	triple = str_replace(' ','',sub) + ' ' + pred + ' ' + obj + ' .';
	array_push(document.query.triple, triple);

}

function buildPattern() {
   
   //This is the collection in select
   // var Cid = str_replace(' ','',document.getElementById("select").childNodes[document.getElementById("select").selectedIndex].value);
   var Cid = document.getElementById('select').value;
   
   //triple for collection items
   var sub1 = '?'+str_replace(' ','',document.getElementById("select").childNodes[document.getElementById("select").selectedIndex].attributes["varName"].value);
   var pred1 ='rdf:type';
   var obj1	 = ':C' + Cid;
   var triple = sub1 + ' ' +  pred1  + ' ' + obj1 + ' . ';

   triple += '\n OPTIONAL { ' + sub1 + ' rdfs:label ' + sub1 + 'Label . } ';
   //queryAddTriple(sub1, pred1, obj1)
  
   //This is the rule where the user has navigated into another collection (or not)
   var pogoRule = document.getElementById(Cid+'_rules').value;
   
	//Does pogoRule have a object_id
	var tripleOrder = array();
	

	
	while(pogoRule!=''){
		var currRule = document.rules[pogoRule.replace(/^:R/,'')];
		var tmp = array();
		var rule_id = currRule.rule_id;
		tmp.subject = '?'+str_replace(' ','',currRule.subject);
		tmp.predicate = ':R'+currRule.rule_id;
			if(currRule.object_id!='')
			{
			tmp.object = '?'+str_replace(' ','',currRule.object);
			
			//now there is a new pogo rule
			pogoRule = document.getElementById(currRule.object_id+'_rules').value;
			}
		else {
			//is it not empty?
			if(document.getElementById('operators_' + rule_id)!=null)
			var op1 = document.getElementById('operators_'+rule_id).value;
			
			
			if(document.getElementById('attr_val_'+rule_id)!=null)
			var obj2 = 	document.getElementById('attr_val_'+rule_id).value;
			objVarName = '?'+str_replace(' ','',currRule.object);

			if(obj2){
				if(op1=='FILTER')
				{
				obj2 = objVarName + ' FILTER regex(' +objVarName+' , "' + obj2 + '")';
				}
				else if(op1=='=')
				{
				obj2 = objVarName + ' FILTER regex(' +objVarName+' , "^' + obj2 + '$")';
				}
			tmp.object = obj2;
			}
			else {
			   tmp.object =  objVarName 
			}
			pogoRule = '';
		}
		triple += '\n' + tmp.subject + ' ' + tmp.predicate + ' ' + tmp.object + ' . ';
		array_push(tripleOrder,rule_id);
		}
		
	
	
	 
	 if(document.query){
	 for (q = 0; q < document.query.triple.length; q++) {
	   triple += '\n' + document.query.triple[q];
	 }
	 }
	
	//if(document.getElementById('all_tuples').checked) {
	if(document.getElementById('all_tuples').checked || document.getElementById(Cid+'_rules').value=='all') {
	
	  // Need to find all the rule objects that shape this tuple
	  if(document.getElementById('select').value!='*')    {
		  var Rules = document.getElementById(Cid+'_rules').childNodes;
	  	  for (i = 0; i < Rules.length; i++) {
		   if (!Rules[i].disabled && !in_array(Rules[i].getAttribute('rule_id'), tripleOrder)) {
		       	var tmpObj = '?' + str_replace(' ','', Rules[i].attributes["object"].value);
				triple += '\n OPTIONAL { ' + sub1 + ' ' + Rules[i].value + ' ' +  tmpObj + ' . }';
		   }
		  }
	  }
	 
	}
	
	var query = document.getElementById('query').innerHTML;
	if(query){
	var p=str_replace(/WHERE(.|\n)*/.exec(query),'',query);
	var q=/(.|\n*)WHERE\s*{(.|\n*)*}/.exec(query,'i');
	var r=str_replace("\n",'',q[0]);
	t = /WHERE\s*{(.*)}/.exec(r);
	t=t[1] + '\n' + '\t' + triple;
	 query = p + '\nWHERE \n{' + t + '\n}';
	}
	else {
	    var prefix = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>';
		var query =   prefix  + '\n' + 'SELECT * \n FROM <'+document.getElementById('uri_target').value +'> \n WHERE {\n' + triple + '\n}';
		
	}
	 document.getElementById('query').value = query;

  
}

function navigate_ontology(Cid, Rules, ind,parent_id) {
	
	
	//now clean the div and create it again
	if(!document.getElementById(Cid+'_value_box'))
	{
	var varBox = document.createElement('span');
	varBox.id = Cid+'_value_box';
	//append to parent id
	document.getElementById(parent_id).appendChild(varBox);
	}
	else {
	    varBox = document.getElementById(Cid+'_value_box');
		varBox.innerHTML = '';
	}
	//Find out which index is selected:
	var ind = document.getElementById(Cid+'_rules').selectedIndex;

	//Retrieve information on that rule
	var rule_info = Rules[ind];
	
	
	 if(rule_info.attributes['object_id'].value=='C' || rule_info.attributes['object_id'].value=='')
	{
	  
	  document.navigation = rule_info.attributes['rule_id'].value;
	  newSpan = document.createElement('span');
	  newSpan.class="operator";
	  newSpan.id = "operator_"+substr(rule_info.value,2,rule_info.value.length);
	  varBox.appendChild(newSpan);
	 
	display_input_box(rule_info.attributes['rule_id'].value,newSpan.id);
	
	}
	else {
	  
	  var divTxtBox = document.createElement('div');
	  divTxtBox.id = rule_info.attributes['rule_id'].value+'_value';
	  divTxtBox.innerHTML = '';
		
	  //Append the new div to parentid element
	  varBox.appendChild(divTxtBox);
		
		var objToMatch = rule_info.attributes['object_id'].value.replace(/^C/,'');
	  
	  
	  //Now retrieve the rules where the indicared object ID is treated as subject.
	  var thisTd = document.getElementById('value_box_td');
	  var newDiv = document.createElement('div');
	  newDiv.id = objToMatch+'_nav';
	  newDiv.collection_id =  objToMatch;
	  thisTd.appendChild(newDiv);
	  var replace=1;
	  ruleConstrain(objToMatch, objToMatch+'_rules',newDiv.id,replace);
	  //Keep running it until we run out of collections
	  //Find all the childNodes of rules that have this object_id as their subject
	 
	 //alert("You have chosen a rule that point to another collection. I am still developing this feature. Come back soon and your wishes will come true :-).");
	// build_new_ruleSet(rule_info, "query_builder_table");
	}
}

function  display_input_box(rule_id, parent_id) {
     //Ok, so this is a literal object - display the regualr text box
	
	var op_sel = '<select id="operators_'+rule_id+'"><option value="FILTER">~</option><option>=</option><option>></option><option><</option></select>';
   
	
	document.getElementById(parent_id).innerHTML = op_sel + '<input type="text" id="attr_val_'+rule_id+'">';
	//document.getElementById('where_value_td').innerHTML ='<input type="text" id="attr_val">';
}

function  build_new_ruleSet(rule_info, parent_id) {
     
	 	  
	  next_subject_id = substr(rule_info.attributes['object_id'].value, 1,rule_info.attributes['object_id'].value.length)
	  
	  //now choose the options;
	  var allRules = document.getElementById('rules').rules;
	  var activeRules = new Array();
	  for (i = 0; i < allRules.length; i++) {
	      if(allRules[i].subject_id == next_subject_id)	 {
				array_push(activeRules, allRules[i]);
		  }
		  if(allRules[i].rule_id == substr(rule_info.value, 2, rule_info.value.length)	  )
		  {
		  rule= allRules[i];
		  }
	  }
	  document.navigation = rule['rule_id'];
	  newTr = document.createElement('tr');
	  newTr.class = "rules_box";
	  newTd_a = document.createElement('td');
	  newTr.appendChild(newTd_a);
	  newTd = document.createElement('td');
	  newTd.id ='where_'+rule['rule_id']; 
	  newTr.appendChild(newTd);
	  document.getElementById(parent_id).appendChild(newTr);
	  
	  //This means also a new triple for the query
	  queryAddTriple('?'+rule['subject'], ':R'+rule['rule_id'], '?'+str_replace(' ','',rule['object']));
	  ruleDisplay(next_subject_id, activeRules, "rules_box_"+rule['subject_id'],'where_'+rule['rule_id'], 0);
	  

	}

function when_enter_grab_public_projects(url,key) {
	if(event.keyCode==13)
	if(!url)
		{url = document.getElementById('s3db_deployment').value;}
	if(!key)
		{url = document.getElementById('s3db_key').value;}
}